package fr.cephb.operonj.tools.cmdline.remapper;

import java.util.HashSet;
import java.util.Set;

import com.sleepycat.bind.tuple.TupleBinding;
import com.sleepycat.je.DatabaseConfig;
import com.sleepycat.je.DatabaseException;
import com.sleepycat.je.Environment;
import com.sleepycat.je.Transaction;

import fr.cephb.operonj.core.bio.ChromPosition;
import fr.cephb.operonj.core.db.binding.ChromPositionBinding;
import fr.cephb.operonj.core.db.binding.SetOfStringsBinding;
import fr.cephb.operonj.core.db.comparator.ChromPositionComparator;
import fr.cephb.operonj.core.je.PrimaryDB;

public class PositionToSnpDB
	extends PrimaryDB<ChromPosition, Set<String>>
	{
	private int buildId;
	private ChromPositionBinding keyBinding=new ChromPositionBinding();
	private SetOfStringsBinding valueBinding=new SetOfStringsBinding();
	private static final String DEFAULT_NAME="position2snp_build_";
	
	private static DatabaseConfig setSorter(DatabaseConfig cfg)
		{
		cfg.setBtreeComparator(ChromPositionComparator.class);
		return cfg;
		}
	
	public PositionToSnpDB(Environment env, Transaction txn,
			int buildId,
			DatabaseConfig dbConfig) throws DatabaseException
		{
		super(env, txn, DEFAULT_NAME+buildId, setSorter(defaultDbCfg(env,dbConfig)));
		this.buildId=buildId;
		}
	
	public void add(Transaction txn,int chromId,int start,int end,String name)
		throws DatabaseException
		{
		assert(start<=end);
		for(int i=start;i<end;++i )
			{
			ChromPosition cp=new ChromPosition(chromId,i);
			Set<String> set=this.get(txn,cp);
			if(set==null) set=new HashSet<String>();
			set.add(name);
			put(txn,cp,set);
			}
		}
	
	
	public void remove(Transaction txn,int chromId,int start,int end,String name)
	throws DatabaseException
		{
		assert(start<=end);
		for(int i=start;i<end;++i )
			{
			ChromPosition cp=new ChromPosition(chromId,i);
			Set<String> set=this.get(txn,cp);
			if(set==null) continue;
			set.remove(name);
			put(txn,cp,set);
			}
		}
	
	public int getBuildId()
		{
		return buildId;
		}
	
	@Override
	public String getDefaultName()
		{
		return DEFAULT_NAME+getBuildId();
		}

	@Override
	public TupleBinding<ChromPosition> getKeyBinding()
		{
		return keyBinding;
		}

	@Override
	public TupleBinding<Set<String>> getValueBinding()
		{
		return valueBinding;
		}
	
	
	}
